package org.coldor.battlegame.gameserver;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.coldor.battlegame.map.GameMap;
import org.coldor.battlegame.map.MapLoader;
import org.coldor.battlegame.map.MapLoaderFactory;
import org.coldor.battlegame.userserver.ClientStub;

public class GameServer 
{
	class Player {
		public List<Action> think() {
			//	TODO
			return null;
		}
		
		public void performActionAck(boolean ack) {
			//	TODO
		}
		
		public boolean isAlive() {
			//	TODO
			return false;
		}
		
		public void annouceDeath() {
			//	TODO
		}
		
		public void announceVictory() {
			//	TODO
		}
		
		public void announceGameOver(Player winner) {
			//	TODO
		}
		
		public Player(ClientStub client) {
			//	TODO
		}
		
		public void sayHello(String msg) {
			//	TODO
		}
	}
	
	class Action {
		
	}
	
	Map<String, String> mConfig = null;
	int mMapID = -1;
	List<Player> mPlayerList = null;
	GameMap gameMap = null;
	
	public GameServer(int mapID, List<ClientStub> userList, Map<String, String> config)
	{
		mConfig = config;
		mPlayerList =  new ArrayList<Player>();
		for (ClientStub client : userList)
			mPlayerList.add(new Player(client));
		mMapID = mapID;
	}
	
	public void run()
	{
		loadMap(mMapID);
		connectUsers(mPlayerList);
		mainLoop();
	}
	
	void mainLoop()
	{
		LinkedList<Player> livePlayerQueue = new LinkedList<Player>();
		for (Player player: mPlayerList)
			livePlayerQueue.push(player);
		
		assert (livePlayerQueue.size() > 0);
		
		while (true) {
			Player cp = livePlayerQueue.pop();
			if (livePlayerQueue.isEmpty()) {
				cp.announceVictory();
				gameOver(cp);
				break;
			}
			
			List<Action> actionSequence = cp.think();
			boolean result = checkAndPerform(cp, actionSequence);
			cp.performActionAck(result);
			if (cp.isAlive())
				livePlayerQueue.push(cp);
			else
				cp.annouceDeath();
		}
	}
	
	boolean checkAndPerform(Player player, List<Action> actions) {
		//	TODO
		return false;
	}
	
	void gameOver(Player winner) {
		for (Player player : mPlayerList)
			player.announceGameOver(winner);
	}
	
	void connectUsers(List<Player> mPlayerList)
	{
		//	Assume ClientStub contains a connection to each client
		
		//	testing connection status 
		for (Player player : mPlayerList)
		{
			player.sayHello("Greetings from GameServer");
		}
	}
	
	void loadMap(int mapID)
	{
		MapLoader loader = MapLoader.getInstance();
		gameMap = loader.load(mapID);
	}
}
